/**
*  \file interpol_u16_u16.c
*
*  \brief
*
*  \author Michael J. Hohmann  <michael.hohmann@linde-mh.de>
*
*  added for volatege measurement
*
*/

/*===============================================[ private includes  ]================================================*/
#include "interpol_u16_u16.h"
#include "../assertor/assertor.h"
#include "../saturated/saturated.h"

/*===============================================[ private defines   ]================================================*/

/*===============================================[ private datatypes ]================================================*/

/*===============================================[ private variables ]================================================*/

/*===============================================[ private functions ]================================================*/

/*===============================================[ inline functions  ]================================================*/

/*===============================================[ public functions  ]================================================*/

/** Interpolation.
*
*  Perform a linear interpolation of a table with 16 bit signed nodes of arbitrarily size.
*  The values of the x-nodes have to be in ascending order.
*
*  \param me table info
*  \param value The X-Value.
*
*  \return The interpolated value.
*/
U16 interpol_u16_u16(struct interpol_u16_u16_obj const *me, U16 value)
{
   ASSERTOR_PRE(NIL != me, "NULL is not allowed as object pointer.");
   {
      pal_size_t min = 0;
      pal_size_t max = me->count - 1;

      /* perform a binary search over table elements. */
      while ((max - min) > 1)
      {
         pal_size_t cursor = min + (max - min) / 2;
         if (me->x[cursor] > value)
         {
            max = cursor;
         }
         else
         {
            min = cursor;
         }
      }

      /* calculate interpolation of two immediate neighbour nodes */
      {
         S32 x1 = me->x[min];
         S32 y1 = me->y[min];

         S32 x2 = me->x[max];
         S32 y2 = me->y[max];
         S32 xval = value;
         S32 rv = ( ( (y2 - y1) * (xval-x1) ) / (x2 - x1)) + y1;
         ASSERTOR_POST( ( rv >= U16_MIN ) && ( rv <= U16_MAX ), "Result of computation does not fit into type of return value" );

         return saturated_cast_S32_U16( rv );
      }
   }
}

RC interpol_u16_u16_construct( struct interpol_u16_u16_obj *me, pal_size_t count, U16 const * p_x, U16 const * p_y )
{
	me->count= count;
	me->x= p_x;
	me->y= p_y;
	return RC_SUCCESS;
}


/***********************************************************************************************************************
*                             Copyright 2018 Linde Material Handling. All rights reserved.                             *
***********************************************************************************************************************/
